/* File: NILogin.m - (Interactive) Unix shell version of NILoginPanel
 *
 * By: Christopher Lane (lane@sumex-aim.stanford.edu)
 *
 * Date: 10 November 1992
 *
 * Copyright: 1991 & 1992 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 *
 * Warning: This code doesn't work, NILoginPanel doesn't perform as advertised.
 */

#import <stdlib.h>
#import <getopt.h>
#import <nikit/NIDomain.h>
#import <nikit/NILoginPanel.h>
#import <appkit/Application.h>

#define USAGE "usage: %s [-d domain] [-u user] [-p prompt] [-b]\n"
#define INSTRUCTION "This change to the NetInfo database requires privilege, please log in as an authorized user."
#define EXIT_USAGE (2)

#define LOCAL "."

void main(int argc, char *argv[])
{
	ni_status nstatus;
	id panel, domain;
	BOOL enableUser = YES;
	ni_name domainName = LOCAL;
	int context, option, status = EXIT_SUCCESS;
	const char *userName = "root", *instruction = INSTRUCTION;
	
	context = [(NXApp = [Application new]) activateSelf:YES];
	
	panel = [NILoginPanel new];
	
	domain = [[NIDomain alloc] init];
	
	while ((option = getopt(argc, argv, "d:u:p:b")) != EOF)
		switch (option) {
		case 'd': domainName = (ni_name) optarg; break;
		case 'u': userName = optarg; break;
		case 'p': instruction = optarg; break;
		case 'b': enableUser = NO; break;
		default : status = EXIT_USAGE;
		}
	if (optind < argc) status = EXIT_USAGE;
	
	if (status == EXIT_USAGE) (void) fprintf(stderr, USAGE, [NXApp appName]);
	else if ((nstatus = [domain setConnection:domainName]) != NI_OK)
		(void) fprintf(stderr, "%s\n", ni_error(nstatus));
//	else if ([panel runModal:NXApp inDomain:[domain getDomainHandle]])
	else if ([panel runModal:NXApp inDomain:[domain getDomainHandle] withUser:userName withInstruction:instruction allowChange:enableUser])
		status = ([panel isValidLogin:NXApp]) ? EXIT_SUCCESS : EXIT_FAILURE;
	else status = EXIT_FAILURE;
	
	[panel free];
	[[domain disconnectFromCurrent] free];
	
	if (context) (void) [NXApp activate:context];
	
	[NXApp free];
	
	exit(status);
}
